import {Component, OnInit} from '@angular/core';
import {ModalController, NavParams} from '@ionic/angular';
import {HttpService} from '../../shared/service/http.service';
import {AppGlobalService} from '../../shared/service/app-global.service';

@Component({
    selector: 'app-city-modal',
    templateUrl: './city-modal.component.html',
    styleUrls: ['./city-modal.component.scss']
})
export class CityModalComponent implements OnInit {

    data: any;
    citys: any = {};
    map: any;
    indexs: any;
    selectedCity:any;

    constructor(private navParams: NavParams,
                private modalCtrl: ModalController,
                private http: HttpService,
                private appGlobalService: AppGlobalService) {
    }

    ngOnInit() {
        this.map = new Map();
        this.data = JSON.parse(this.navParams.data.value);
        this.data.table.condition = [{field: 'type', value: '2'}];
        const table = {
            'table': this.data.table
        };
        const params = {
            content: table,
            id: this.data['id'],
            sessionId: localStorage.getItem('sessionId')
        };
        // 请求获取新数据
        this.http.post('application/submit', params, res => {
            // 请求数据成功
            if (res.data.data) {
                const s = new Set();
                this.indexs = [];
                let resList = res.data.data;
                // let resList = [{code: 11, name: '北京', index: 'B'}, {code: 12, name: '天津', index: 'T'},
                //     {code: 13, name: '澳门', index: 'A'}, {code: 15, name: '奥奇', index: 'A'}];
                for (let item of resList) {
                    s.add(item.index);
                    this.map.set(item.name, item);
                }
                this.indexs = Array.from(s).sort();
                this.indexs.map(index => {
                    this.citys[index] = [];
                    resList.map(city => {
                        if (index === city['index']) {
                            this.citys[index].push(city);
                        }
                    });
                });
            } else {
                // 请求数据失败
                this.appGlobalService.showToast(res['message'], 2000, 'middle');
            }
        });
    }

    getItems(ev: any) {
        const val = ev.target.value;
        const city = this.map.get(val);
        if (city) {
            this.indexs = [city.index];
            this.citys[city.index] = [city];
        }
    }

    selectCity(item){
        item.checked = true;
        this.selectedCity = item;
    }

    dismiss() {
        this.modalCtrl.dismiss(this.selectedCity);
    }
}
